import { orderBy } from 'lodash-es'

export function deepTree(list: any[], sort?: 'desc' | 'asc'): any[] {
  const result: any[] = []
  const map: any = {}

  orderBy(list, 'orderNum', sort)
    .map((item) => {
      map[item.id] = { ...item }
      return item
    })
    .forEach((item) => {
      const parent = map[item.parentId]
      const current = map[item.id]

      if (parent) {
        ;(parent.children || (parent.children = [])).push(current)
      } else {
        result.push(current)
      }
    })

  return result
}
